package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.ManagerConstants;
import com.powernode.domain.SysMenu;
import com.powernode.ex.handler.BusinessException;
import com.powernode.mapper.SysMenuMapper;
import com.powernode.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.SysMenuServiceImpl")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService{

    @Autowired
    private SysMenuMapper sysMenuMapper;


    @Override
    @Cacheable(key = "#userId")
    public Set<SysMenu> queryUserMenuListByUserId(Long userId) {
        Set<SysMenu> sysMenus = sysMenuMapper.selectUserMenuListByUserId(userId);
        return transformTree(sysMenus,0L);
    }



    /**
     * 集合转换为树结构：
     *  1.树的深度：<=2
     *
     *  2.树的深度：未知
     *
     *
     * @param sysMenus
     * @param pid
     * @return
     */
    private Set<SysMenu> transformTree(Set<SysMenu> sysMenus, Long pid) {
        // 情况1：深度<=2
        // 获取根节点
        /*Set<SysMenu> roots = sysMenus.stream()
                .filter(sysMenu -> sysMenu.getParentId().equals(pid))
                .collect(Collectors.toSet());
        // 获取每一个根节点的子节点集合
        // 循环遍历根节点集合
        roots.forEach(root -> {
            // 从菜单集合中过滤出节点的pid与当前根节点的menuId一致的节点集合
            Set<SysMenu> child = sysMenus.stream()
                    .filter(sysMenu -> sysMenu.getParentId().equals(root.getMenuId()))
                    .collect(Collectors.toSet());
            root.setList(child);
        });*/

        // 情况1：深度未知
        // 获取根节点
        Set<SysMenu> roots = sysMenus.stream()
                .filter(sysMenu -> sysMenu.getParentId().equals(pid))
                .collect(Collectors.toSet());
        roots.forEach(r -> r.setList(transformTree(sysMenus,r.getMenuId())));
        return roots;
    }


    @Override
    @Cacheable(key = ManagerConstants.ALL_SYS_ROLE)
    public List<SysMenu> queryAllSysMenuList() {
        return sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                .orderByDesc(SysMenu::getOrderNum)
        );
    }

    @Override
    @CacheEvict(key = ManagerConstants.ALL_SYS_ROLE)
    public Integer addSysMenu(SysMenu sysMenu) {
        // 获取权限类型
        Integer type = sysMenu.getType();
        if (0 == type) {
            sysMenu.setParentId(0L);
        }
        return sysMenuMapper.insert(sysMenu);
    }

    @Override
    @CacheEvict(key = ManagerConstants.ALL_SYS_ROLE)
    public Integer modifySysMenu(SysMenu sysMenu) {
        // 获取权限类型
        Integer type = sysMenu.getType();
        if (0 == type) {
            sysMenu.setParentId(0L);
        }
        return sysMenuMapper.updateById(sysMenu);
    }

    @Override
    @CacheEvict(key = ManagerConstants.ALL_SYS_ROLE)
    public Integer removeSysMenuById(Long menuId) {
        // 查询当前节点的子节点
        List<SysMenu> list = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getParentId, menuId)
        );
        if (!CollectionUtils.isEmpty(list) && list.size() != 0) {
            throw new BusinessException("当前节点包含子节点，不可删除");
        }
        return sysMenuMapper.deleteById(menuId);
    }
}
